// pages/address/address.js
const config = require("../../config");
const app = getApp();
Page({
    data: {},
    onLoad: function (options) {
        app.toast.init();
        this.setData({
            height: app.window.height
        })
    },

    onShow: function () {
        app.http.get(app.config.address.list_url, {
        }).then(result => {
            this.setData({ list: result.data })
        })
    },

    //删除地址
    delete_address: function (evt) {
        var obj = this;
        wx.showModal({
            title: "提示",
            content: "确认删除该地址？",
            confirmText: "确定",
            canceltext: "取消",
            success: (res) => {
                if (res.confirm) {
                    app.http.get(config.address.remove_url, {
                        data: { id: evt.currentTarget.dataset.id },
                    }).then(res => {
                        this.toast.show({ title: "删除成功" });
                        var add = this.data.list.filter(function (o) {
                            return o.id != evt.currentTarget.dataset.id;
                        });
                        this.setData({ list: add });
                    })
                }
            }
        });
    },


    edit_address: function (evt) {
        var id = evt.currentTarget.dataset.id;
        wx.navigateTo({
            url: id ? ('./edit?id=' + id) : './edit',
        })
    },


    select_address: function (evt) {
        var id = evt.currentTarget.dataset.id;
        app.global_data.address = id;
        wx.navigateBack({
            delta: 1
        });
    },


    set_default: function (evt) {
        var id = evt.currentTarget.dataset.id;
        this.toast.loading({
            title: ""
        });
        var obj = this;
        app.http.get(config.address.set_default_url, {
            data: { id: id },
        }).then(res => {
            this.toast.hide();
            this.toast.show({
                title: "设置成功",
                duration: 3000,
            });
            var arr = this.data.list.map(function (o) {
                o.default = o.id == id;
                return o;
            });
            this.setData({ list: arr });
        })
    },

    addNewAddress() {
        wx.chooseAddress({
            success: function (res) {
                console.log(res.userName)
                console.log(res.postalCode)
                console.log(res.provinceName)
                console.log(res.cityName)
                console.log(res.countyName)
                console.log(res.detailInfo)
                console.log(res.nationalCode)
                console.log(res.telNumber)
            }
        })
    }

})